#pragma once

#include <iostream>
#include <string>
#include <memory>
#include <functional>
#include <thread>
#include <cstdlib>
#include <cstring>
#include <cerrno>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "err.hpp"
#include "loop_queue.hpp"
#include "thread_pool.hpp"
#include "task.hpp"

namespace tcp
{

const int backlog = 16;

class tcp_server;

struct thread_args
{
public:

    thread_args(tcp_server* tp, int fd, const std::string& who)
        : ts(tp), sock(fd), cli(who)
    {}

public:
    tcp_server* ts;
    int sock;
    std::string cli;
};

class tcp_server
{
public:
    using func_t = std::function<std::string(const std::string&)>;

public:
    tcp_server(func_t func, uint16_t port) 
        : _listen_sock(0), _port(port), _quit(false), _func(func)
    {}

    ~tcp_server()
    {
        close(_listen_sock);
    }

    void init()
    {
        // 1. socket 
        _listen_sock = socket(AF_INET, SOCK_STREAM, 0);
        if (_listen_sock < 0) 
        {
            std::cerr << "socket error" << std::endl;
            exit(SOCKET_ERR);
        }
        std::cout << "socket success " << _listen_sock << std::endl;

        // 2. bind
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_addr.s_addr = INADDR_ANY;
        local.sin_port = htons(_port);

        if (bind(_listen_sock, (struct sockaddr*)&local, sizeof(local)) < 0) 
        {
            std::cerr << "bind error" << std::endl;
            exit(BIND_ERR);
        }
        std::cout << "bind success" << std::endl;

        // 3. listen
        if (listen(_listen_sock, backlog) < 0)
        {
            std::cerr << "listen error" << std::endl;
            exit(LISTEN_ERR);
        }
        std::cout << "listen success" << std::endl;
    }

    void start()
    {
        // signal(SIGCHLD, SIG_IGN);

        while (!_quit)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sock = accept(_listen_sock, (struct sockaddr*)&peer, &len);
            if (sock < 0)
            {
                std::cerr << "accept error" << std::endl;
                continue;
            }

            std::string cip = inet_ntoa(peer.sin_addr);
            uint16_t cport = ntohs(peer.sin_port);
            std::string cli = '[' + cip + ':' + std::to_string(cport) + ']';

            std::cout << "accept success sock " << sock << " form " << _listen_sock 
                      << ", " << cli << std::endl;

            //v1
            // service(sock, cli);
            
            //v2
            /*
            pid_t id = fork();
            if (id < 0)
            {
                std::cerr << "fork failed" << std::endl;
                close(sock);
                continue;
            }
            else if (id == 0)
            {
                close(_listen_sock);

                if (fork() > 0) exit(0); // 孤儿孙子进程提供服务，孤孙进程由操作系统负责回收
                service(sock, cli);

                close(sock);
                exit(0);
            }
            else
            {
                close(sock); // hand it to childproc, must close it to save resources
                pid_t res = waitpid(id, nullptr, 0);
                if (res == id)
                    std::cout << "wait childproc success " << id << std::endl;
            }
            */

            //v3
            /* 
            pthread_t tid;
            thread_args* data = new thread_args(this, sock, cli);
            pthread_create(&tid, nullptr, routine, data);
            pthread_detach(tid);
            
            std::thread th(&tcp_server::service, this, sock, cli);
            th.detach();
            */

            //v4    
            task t(&tcp_server::service, this, sock, cli);
            thread_pool<task>::get_instance()->push(t);
        }
    }

    static void* routine(void* args)
    {
        thread_args* td = static_cast<thread_args*>(args);
        td->ts->service(td->sock, td->cli);

        delete td;
        return nullptr;
    }

    void service(int sock, const std::string& cli)
    {
        char buf[1024] = {0};
        while (true)
        {
            ssize_t s = recv(sock, buf, sizeof(buf) - 1, 0);
            if (s > 0)
            {
                buf[s] = 0;
                std::string res = _func(buf);
                std::cout << cli << "# " << res << std::endl;

                send(sock, res.c_str(), res.size(), 0);
            }
            else if (s == 0)
            {
                close(sock);
                std::cout << cli << " quit, cancel service" << std::endl;
                break;
            }
            else
            {
                close(sock);
                std::cerr << "recv error " << strerror(errno) << std::endl;
                break;
            }
        }
    }

private:
    int _listen_sock;
    uint16_t _port;
    bool _quit;
    func_t _func;
};

}

